#coding=utf-8
import sys

from uliweb.orm import (get_model, set_dispatch_send, Begin, 
    Commit, Rollback, NotFound)
import logging

set_dispatch_send(False)

def call(args, options, global_options):
    from uliweb import function
    from uliweb.manage import make_application

    app = make_application(start=False, debug_console=False, debug=False)
    Begin()
    try:
        process(args[1:], options, global_options)
        Commit()
    except:
        Rollback()
        import traceback
        traceback.print_exc()

def process(args, options, global_options):
    Task = get_model('tasks_develop')
#    Task.modified_user.auto_now = False
    Task.modified_user.default = None
    n = 0
    for t in Task.all():
        if t._tx_ != t.requirement._tx_:
            t.tx = t.requirement._tx_
            t.save()
            n += 1
            
    print 'Total %d tasks processed' % n
    
    Details = get_model('tasks_details')
    Details.modified_user.default = None
    n = 0
    x = 0
    for t in Details.all():
        try:
            if t._requirement_ and t._tx_ != t.requirement._tx_:
                t.tx = t.requirement._tx_
                t.save()
                n += 1
        except NotFound, e:
            t.requirement = None
            t.tx = None
            t.save()
            x += 1
    
    print "Total %d tasks_details processed, %d requirements can't be found" % (n, x)
    